﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedRegService;

using MedicWeb.MedicService;

namespace MedicWeb.forms.Editors
{
    public partial class MedRegDoctorList : SessionPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            //var mr = new Service1();
            
            
            Form.Action = ResolveUrl("~/forms/Editors/RMRDoctorList.aspx");
            
            
            //var guid = new Guid("5A4CDD9F-A102-4005-9A96-0A9571BC0F82");

            string id = Request.QueryString["id"];

            if (id != null)
            {
                Form.Action += "?id=" + id;
                if (!IsPostBack && id != "0")
                {
                    var guid = (new MainService()).LoadInstitution(GetSession(), Convert.ToInt32(id)).Rmr;
                    DataGrid1.DataSource = SetupDataSource(guid, "А", 20);
                    DataGrid1.DataBind();
                    
                }
            }
            
        }

        /*
        private FlatEmployee[] generate(string surname) {
            Thread.Sleep(2000);
            if (surname.Length < 3) {
                return new FlatEmployee[0];
            }
            var result = new List<FlatEmployee>();
            for (int i = 0; i < 300; i++) {
                var flatEmployee = new FlatEmployee() {
                    AcademicDegree = "AcademicDegree",
                    Address = "Address",
                    BearthYear = 1999,
                    Category = "Category",
                    Experience = new decimal(10),
                    Fired = false,
                    ID = new Guid("E402B0C1-17DC-459E-92D9-F3709FDB812A"),
                    Name = "Name" + DateTime.Now.ToLongTimeString(),
                    Patromane = "Patromane",
                    Post = "Post",
                    Sex = "Sex",
                    Speciality = "Speciality",
                    Surname = surname + "..." + i
                };
                result.Add(flatEmployee);
            }
            return result.ToArray();
        }

        */

        protected DataTable SetupDataSource(Guid guid, string surname, int count)
        {

            Session.Remove("ds");
            var mr = new Service1();
            /* if (Session["ds"] == null)
            { */
                var query = mr.GetFlatEmployeeListByLPUandSurname(guid, surname, count);
            //var query = generate(surname);
                
                // Create the schema of the DataTable.
                DataTable dt = new DataTable();
                DataColumn dc;
                dc = new DataColumn("Id", typeof(Guid)); dt.Columns.Add(dc);
                dc = new DataColumn("Surname", typeof(string)); dt.Columns.Add(dc);
                dc = new DataColumn("Name", typeof(string)); dt.Columns.Add(dc);
                dc = new DataColumn("Patroname", typeof(string)); dt.Columns.Add(dc);
                dc = new DataColumn("Post", typeof(string)); dt.Columns.Add(dc);
                dc = new DataColumn("BeathYear", typeof(int)); dt.Columns.Add(dc);


                // Add rows to the DataTable.
                IEnumerator emplEnum = query.OrderBy(e => e.Surname).GetEnumerator();
                FlatEmployee ne;
                while (emplEnum.MoveNext())
                {
                    ne = emplEnum.Current as FlatEmployee;
                    DataRow row = dt.NewRow();
                    row["Id"] = ne.ID;
                    row["Surname"] = ne.Surname;
                    row["Name"] = ne.Name;
                    row["Patroname"] = ne.Patromane;
                    row["Post"] = ne.Post;
                    row["BeathYear"] = ne.BearthYear;
                    dt.Rows.Add(row);
                }
                
                Session["ds"] = dt;
                Session["all"] = query;
                Session["lpuguid"] = guid;
                return dt;

            /* }
            else
            {
                return (DataTable)Session["ds"];
            } */
        }

        protected DataTable BindDataSource ()
        {
            if (Session["ds"] == null)
            {
                return null;
            }
            return (DataTable)Session["ds"];
            
        }


        
        protected void DataGrid1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            DataGrid1.PageIndex = e.NewPageIndex;
            DataGrid1.DataSource = BindDataSource();
            DataGrid1.DataBind();
        }


        protected void DataGrid1_Sorting(object sender, GridViewSortEventArgs e)
        {


            //Retrieve the table from the session object.
            DataTable dt = ((DataTable)Session["ds"]);

            if (dt == null) return;
            //Sort the data.
            dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
            DataGrid1.DataSource = Session["ds"];
            DataGrid1.DataBind();
        }

        private string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

        protected void btnRMRSearch_Click(object sender, EventArgs e)
        {
            var txt = tbRMRSearch.Text;
            var dt = (DataTable) Session["ds"];
            var guid = (Guid) Session["lpuguid"];
            if (dt != null & guid != null)
            {
                Session.Remove("ds");
                DataGrid1.DataSource = SetupDataSource(guid, txt, 0);
                DataGrid1.DataBind();
                
                
            }
        }

        protected void DataGrid1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            foreach (GridViewRow row in DataGrid1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    row.Attributes["onmouseover"] =
                       "this.style.cursor='hand'; this.style.textDecoration='bold';";
                    row.Attributes["onmouseout"] =
                       "this.style.textDecoration='none';";
                    // Set the last parameter to True 
                    // to register for event validation. 
                    row.Attributes["onclick"] =
                     ClientScript.GetPostBackClientHyperlink(DataGrid1,
                        "Select$" + row.DataItemIndex, true);
                }
            }
            base.Render(writer);
        }

        protected void DataGrid1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                if (DataGrid1.DataKeys != null)
                {
                    Guid strValue = (Guid) DataGrid1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
                    ViewState["selecteddoctorId"] = strValue;
                }
            } 
        }

        protected void btnSelectRMR_Click(object sender, EventArgs e)
        {
            if (Session["all"] == null | ViewState["selecteddoctorId"] == null)
            {
                // TODO Add Alert
                return;
            }
            var query  = (FlatEmployee[]) Session["all"];
            var id = (Guid)ViewState["selecteddoctorId"];

            FlatEmployee selectedDoctor = query.Where(d => d.ID == id).Select(d => d).First();
            Session["RMRDoctor"] = selectedDoctor;

            Session.Remove("ds");
            Session.Remove("all");
            Session.Remove("lpuguid");
            

        }

        protected void DataGrid1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    cell.Attributes.Add("title", "Нажмите для сортировки");
                }
            }
        }

       

       
        

    }

    

}